package com.dyp.globalexceptionhandler.ctr;

import com.dyp.globalexceptionhandler.model.Book;
import com.dyp.globalexceptionhandler.model.CustomHttpStatusCodeException;
import com.dyp.globalexceptionhandler.model.People;
import com.dyp.globalexceptionhandler.model.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

//使用RestController可以省略在方法上的@ResponseBody注解
@RestController
@RequestMapping(value = "/mvc")
@Api(value = "api for mvc", produces = "application/json;charset=UTF-8")
public class RestfulCtr {


    @ApiOperation(value = "用来测试全局异常处理", httpMethod = "POST", response = People.class)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Success", response = People.class) })
    //    @RequestMapping(value = "people/info/{id}", method = RequestMethod.POST)
    @PostMapping(value = "people/info/{id}")
    public People sayHi4(@PathVariable(name = "id") int id,
                         @RequestParam int num,
                         @RequestBody People people) {
        if(true)
        {
            throw new CustomHttpStatusCodeException("test global exception handler");
        }
        people.setId(id);
        people.setNum(num);
        return people;
    }

    @GetMapping("/global/data/binding/{id}")
    @ApiOperation(value = "用来测试全局数据绑定", httpMethod = "GET", response = String.class)
    public String hello(@PathVariable(name = "id") int id, Model model) {
        System.out.println(id);
        Map<String, Object> map = model.asMap();
        return map.toString();
    }

    @GetMapping("/global/data/process")
    @ApiOperation(value = "用来测试全局数据处理", httpMethod = "GET", response = String.class)
    public String hello1(Date date) {
        return date.toString();
    }

    //测试Date自动转换的时候把GlobalDataProcessing的@ControllerAdvice注释掉
    @PostMapping("/book")
    public Book createBook(@RequestBody Book book){
        System.out.println(book.toString());
        return book;
    }

    @GetMapping("/user/profile")
    public String showUserProfile(
            @ModelAttribute("currentUser") User user,  // 自动注入Model
            Model model) {
        // 方法内无需手动添加，user对象已存在于model中
        System.out.println(model.getAttribute("currentUser"));
        return "user-profile";  // 视图层可通过${currentUser}访问
    }
}
